package com.wangyuan.demo.controller;

import com.wangyuan.demo.entity.User;
import com.wangyuan.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 用户控制器
 *
 * @author Albert
 * @date 2025-06-23 14:52:25
 */
@Controller
@RequestMapping("user")
public class UserController {

    /**
     * 自动注入 UserService 实例，用于处理业务逻辑
     */
    @Autowired
    private UserService userService;

    /**
     * 处理用户注册请求
     *
     * @param user 接收前端JSP页面提交的用户信息
     * @return 返回重定向到登录页面的路径
     */
    @PostMapping("/register")
    public String register(User user) throws UnsupportedEncodingException {
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp?msg=" + URLEncoder.encode(e.getMessage(), "UTF-8");
        }
        // 注册成功后跳转至登录页面
        return "redirect:/login.jsp";
    }

    /**
     * 处理用户登录请求
     *
     * @param username 用户名
     * @param password 密码
     * @param session  HTTP 会话对象，用于存储用户登录状态
     * @return 返回重定向到员工信息列表的路径
     */
    @RequestMapping("login")
    public String login(String username, String password, HttpSession session) throws UnsupportedEncodingException {
        try {
            User dbUser = userService.findByUsernameAndPassword(username, password);
            // 登录成功，保存用户信息到session中
            session.setAttribute("user", dbUser);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/login.jsp?msg=" + URLEncoder.encode(e.getMessage(), "UTF-8");
        }
        return "redirect:/emp/findAll";
    }

}